import 'package:pp_log/pp_log.dart';

abstract class ModelConvertInterceptor {
  dynamic convert(String type, dynamic json);
}

/// 实体bean转化工厂类
class PPBeanFactory {
  static final instance = PPBeanFactory._();
  PPBeanFactory._();

  final List<ModelConvertInterceptor> _interceptors = [];

  void addInterceptor(ModelConvertInterceptor interceptor) {
    _interceptors.add(interceptor);
  }

  static T? generateModel<T>(json) {
    //T.toString() 类名
    try {
      final String type = T.toString();

      if (type == "int") {
        return json;
      } else if (type == "bool") {
        var flag = false;
        if (json is bool) {
          flag = true;
        }
        if (flag) {
          return json;
        }
        return json["result"];
      } else if (type == "String") {
        return json;
      } else if (type == "Map<dynamic, dynamic>") {
        return json;
      }

      for (var interceptor in PPBeanFactory.instance._interceptors) {
        var data = interceptor.convert(type, json);
        if (data != null) {
          return data;
        }
      }

      return null;
    } catch (e) {
      PPLog.d("类[${T.toString()}], 解析数据错误 = $e");
      return null;
    }
  }

  static List<T>? generateModelArray<T>(json) {
    //T.toString() 类名
    try {
      var list = <T>[];
      for (var item in json) {
        var model = PPBeanFactory.generateModel<T>(item);
        if (model != null) {
          list.add(model);
        }
      }
      return list;
    } catch (e) {
      PPLog.d("error = $e");
      return null;
    }
  }
}
